<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信聊天</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.8/css/bootstrap.min.css" rel="stylesheet">
    <!-- Element UI -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/theme-chalk/index.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/7.0.0/css/all.min.css">
    <!-- Vue.js -->
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.14/vue.min.js"></script>
    <!-- Element UI -->
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/index.min.js"></script>
    <style>
        :root {
            --primary: #07c160;
            --dark: #181818;
            --light: #f5f5f5;
            --gray: #f0f0f0;
            --border: #e0e0e0;
            --text-primary: #333;
            --text-secondary: #999;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            background-color: var(--light);
            color: var(--text-primary);
            padding-bottom: 60px;
        }

        .chat-container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            background-color: #f5f5f5;
        }

        .chat-header {
            background: var(--primary);
            color: white;
            padding: 12px 15px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .chat-header .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #e1f3d8;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary);
            font-weight: bold;
            margin-right: 10px;
        }

        .chat-header .header-info {
            flex: 1;
        }

        .chat-header .header-actions {
            display: flex;
        }

        .chat-header .header-actions i {
            margin-left: 20px;
            font-size: 1.2rem;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            display: flex;
            flex-direction: column;
        }

        .message {
            max-width: 75%;
            margin-bottom: 15px;
            position: relative;
        }

        .message.system {
            align-self: center;
            background: #e0e0e0;
            color: #666;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 0.8rem;
            max-width: fit-content;
        }

        .message.sent {
            align-self: flex-end;
        }

        .message.received {
            align-self: flex-start;
        }

        .message-content {
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;
            line-height: 1.4;
        }

        .sent .message-content {
            background: var(--primary);
            color: white;
            border-bottom-right-radius: 2px;
        }

        .received .message-content {
            background: white;
            color: var(--text-primary);
            border-bottom-left-radius: 2px;
        }

        .message-time {
            font-size: 0.7rem;
            color: var(--text-secondary);
            margin-top: 5px;
            text-align: right;
        }

        .sent .message-time {
            color: rgba(255, 255, 255, 0.8);
        }

        .chat-input {
            background: white;
            padding: 10px 15px;
            display: flex;
            align-items: center;
            border-top: 1px solid var(--border);
            position: sticky;
            bottom: 0;
        }

        .chat-input .input-group {
            flex: 1;
            background: var(--gray);
            border-radius: 20px;
            padding: 5px 15px;
            display: flex;
            align-items: center;
        }

        .chat-input input {
            flex: 1;
            border: none;
            background: transparent;
            padding: 8px 0;
            outline: none;
        }

        .chat-input button {
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 10px;
        }

        .friend-list {
            background: white;
            border-radius: 10px;
            margin: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .friend-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid var(--border);
        }

        .friend-item:last-child {
            border-bottom: none;
        }

        .friend-item .avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #e1f3d8;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary);
            font-weight: bold;
            margin-right: 12px;
            font-size: 1.2rem;
        }

        .friend-info {
            flex: 1;
        }

        .friend-name {
            font-weight: 500;
            margin-bottom: 3px;
        }

        .friend-last-message {
            font-size: 0.9rem;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 200px;
        }

        .friend-time {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }

        .unread-badge {
            background: var(--primary);
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7rem;
        }

        .tab-bar {
            position: fixed;
            bottom: 0;
            width: 100%;
            background: white;
            display: flex;
            border-top: 1px solid var(--border);
            padding: 8px 0;
        }

        .tab-item {
            flex: 1;
            text-align: center;
            padding: 5px 0;
            color: var(--text-secondary);
        }

        .tab-item.active {
            color: var(--primary);
        }

        .tab-item i {
            font-size: 1.2rem;
            display: block;
            margin-bottom: 3px;
        }

        .tab-item .tab-text {
            font-size: 0.8rem;
        }

        .chat-list {
            padding-bottom: 60px;
        }

        .welcome-screen {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            padding: 20px;
            text-align: center;
        }

        .welcome-screen .logo {
            font-size: 4rem;
            color: var(--primary);
            margin-bottom: 20px;
        }

        .welcome-screen h2 {
            color: var(--text-primary);
            margin-bottom: 10px;
        }

        .welcome-screen p {
            color: var(--text-secondary);
            margin-bottom: 30px;
        }

        .init-btn {
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 10px 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="chat-container">
            <!-- 聊天界面 -->
            <div v-if="currentView === 'chat'">
                <div class="chat-header">
                    <div class="avatar">{{ currentChat.avatar }}</div>
                    <div class="header-info">
                        <div class="fw-bold">{{ currentChat.name }}</div>
                        <div class="small">在线</div>
                    </div>
                    <div class="header-actions">
                        <i class="fas fa-phone"></i>
                        <i class="fas fa-ellipsis-v ms-3"></i>
                    </div>
                </div>

                <div class="chat-messages" ref="messageContainer">
                    <div v-for="(message, index) in currentMessages" :key="index" 
                         :class="['message', message.type]">
                        <div v-if="message.type === 'system'" class="message-content">
                            {{ message.content }}
                        </div>
                        <template v-else>
                            <div class="message-content">
                                {{ message.content }}
                            </div>
                            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                        </template>
                    </div>
                </div>

                <div class="chat-input">
                    <div class="input-group">
                        <input type="text" v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage">
                        <i class="far fa-smile ms-2 text-muted"></i>
                        <i class="fas fa-plus-circle ms-2 text-muted"></i>
                    </div>
                    <button @click="sendMessage">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>

            <!-- 聊天列表界面 -->
            <div v-else-if="currentView === 'chatList'" class="chat-list">
                <div class="chat-header">
                    <div class="fw-bold">微信</div>
                    <div class="header-actions">
                        <i class="fas fa-search"></i>
                        <i class="fas fa-plus-circle ms-3"></i>
                    </div>
                </div>

                <div class="friend-list">
                    <div v-for="(chat, index) in chatList" :key="index" 
                         class="friend-item" @click="openChat(chat)">
                        <div class="avatar">{{ chat.avatar }}</div>
                        <div class="friend-info">
                            <div class="friend-name">{{ chat.name }}</div>
                            <div class="friend-last-message">{{ chat.lastMessage }}</div>
                        </div>
                        <div class="d-flex flex-column align-items-end">
                            <div class="friend-time">{{ formatTime(chat.lastTime) }}</div>
                            <div v-if="chat.unread > 0" class="unread-badge mt-2">{{ chat.unread }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 欢迎界面 -->
            <div v-else class="welcome-screen">
                <div class="logo">
                    <i class="fab fa-weixin"></i>
                </div>
                <h2>微信</h2>
                <p>随时随地联系朋友和家人</p>
                <button class="init-btn" @click="initApp">初始化聊天数据</button>
            </div>

            <!-- 底部导航栏 -->
            <div class="tab-bar">
                <div class="tab-item active">
                    <i class="fas fa-comment-dots" style="width: 100%;"></i>
                    <span class="tab-text">微信</span>
                </div>
                <div class="tab-item">
                    <i class="fas fa-address-book" style="width: 100%;"></i>
                    <span class="tab-text">通讯录</span>
                </div>
                <div class="tab-item">
                    <i class="fas fa-globe" style="width: 100%;"></i>
                    <span class="tab-text">发现</span>
                </div>
                <div class="tab-item">
                    <i class="fas fa-user" style="width: 100%;"></i>
                    <span class="tab-text">我</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        // IndexedDB 数据库操作类
        class ChatDB {
            constructor() {
                this.dbName = 'WeChatDB';
                this.version = 1;
                this.db = null;
            }

            // 初始化数据库
            init() {
                return new Promise((resolve, reject) => {
                    const request = indexedDB.open(this.dbName, this.version);
                    
                    request.onerror = (event) => {
                        reject('数据库打开失败');
                    };
                    
                    request.onsuccess = (event) => {
                        this.db = event.target.result;
                        resolve(this.db);
                    };
                    
                    request.onupgradeneeded = (event) => {
                        this.db = event.target.result;
                        
                        // 创建聊天记录存储
                        if (!this.db.objectStoreNames.contains('messages')) {
                            const messageStore = this.db.createObjectStore('messages', { keyPath: 'id', autoIncrement: true });
                            messageStore.createIndex('chatId', 'chatId', { unique: false });
                            messageStore.createIndex('timestamp', 'timestamp', { unique: false });
                        }
                        
                        // 创建聊天列表存储
                        if (!this.db.objectStoreNames.contains('chats')) {
                            const chatStore = this.db.createObjectStore('chats', { keyPath: 'id' });
                            chatStore.createIndex('lastTime', 'lastTime', { unique: false });
                        }
                    };
                });
            }

            // 添加消息
            addMessage(message) {
                return new Promise((resolve, reject) => {
                    const transaction = this.db.transaction(['messages'], 'readwrite');
                    const store = transaction.objectStore('messages');
                    const request = store.add(message);
                    
                    request.onsuccess = () => {
                        resolve(request.result);
                    };
                    
                    request.onerror = () => {
                        reject('添加消息失败');
                    };
                });
            }

            // 获取聊天记录
            getMessages(chatId) {
                return new Promise((resolve, reject) => {
                    const transaction = this.db.transaction(['messages'], 'readonly');
                    const store = transaction.objectStore('messages');
                    const index = store.index('chatId');
                    const request = index.getAll(IDBKeyRange.only(chatId));
                    
                    request.onsuccess = () => {
                        // 按时间排序
                        const messages = request.result.sort((a, b) => a.timestamp - b.timestamp);
                        resolve(messages);
                    };
                    
                    request.onerror = () => {
                        reject('获取消息失败');
                    };
                });
            }

            // 添加聊天
            addChat(chat) {
                return new Promise((resolve, reject) => {
                    const transaction = this.db.transaction(['chats'], 'readwrite');
                    const store = transaction.objectStore('chats');
                    const request = store.put(chat);
                    
                    request.onsuccess = () => {
                        resolve(request.result);
                    };
                    
                    request.onerror = () => {
                        reject('添加聊天失败');
                    };
                });
            }

            // 获取所有聊天
            getAllChats() {
                return new Promise((resolve, reject) => {
                    const transaction = this.db.transaction(['chats'], 'readonly');
                    const store = transaction.objectStore('chats');
                    const request = store.getAll();
                    
                    request.onsuccess = () => {
                        // 按最后时间排序
                        const chats = request.result.sort((a, b) => b.lastTime - a.lastTime);
                        resolve(chats);
                    };
                    
                    request.onerror = () => {
                        reject('获取聊天列表失败');
                    };
                });
            }
        }

        // 创建Vue实例
        new Vue({
            el: '#app',
            data() {
                return {
                    currentView: 'welcome', // welcome, chatList, chat
                    db: null,
                    newMessage: '',
                    currentChat: {
                        id: '',
                        name: '',
                        avatar: ''
                    },
                    currentMessages: [],
                    chatList: []
                }
            },
            async mounted() {
                // 初始化数据库
                this.db = new ChatDB();
                try {
                    await this.db.init();
                    console.log('数据库初始化成功');
                } catch (error) {
                    console.error('数据库初始化失败:', error);
                }
            },
            methods: {
                // 初始化应用数据
                async initApp() {
                    // 初始化示例聊天数据
                    const sampleChats = [
                        {
                            id: '1',
                            name: '张三',
                            avatar: '张',
                            lastMessage: '晚上一起吃饭吗？',
                            lastTime: Date.now() - 3600000,
                            unread: 2
                        },
                        {
                            id: '2',
                            name: '李四',
                            avatar: '李',
                            lastMessage: '项目进度如何了？',
                            lastTime: Date.now() - 86400000,
                            unread: 0
                        },
                        {
                            id: '3',
                            name: '工作群',
                            avatar: '群',
                            lastMessage: '王五: 收到',
                            lastTime: Date.now() - 172800000,
                            unread: 0
                        }
                    ];

                    // 保存聊天数据到数据库
                    for (const chat of sampleChats) {
                        try {
                            await this.db.addChat(chat);
                        } catch (error) {
                            console.error('保存聊天失败:', error);
                        }
                    }

                    // 初始化示例消息
                    const sampleMessages = [
                        {
                            chatId: '1',
                            type: 'system',
                            content: '2023年6月15日',
                            timestamp: Date.now() - 86400000
                        },
                        {
                            chatId: '1',
                            type: 'received',
                            content: '你好，在忙吗？',
                            timestamp: Date.now() - 86300000
                        },
                        {
                            chatId: '1',
                            type: 'sent',
                            content: '不忙，有什么事吗？',
                            timestamp: Date.now() - 86200000
                        },
                        {
                            chatId: '1',
                            type: 'received',
                            content: '晚上一起吃饭吗？我请客',
                            timestamp: Date.now() - 3600000
                        }
                    ];

                    // 保存消息到数据库
                    for (const message of sampleMessages) {
                        try {
                            await this.db.addMessage(message);
                        } catch (error) {
                            console.error('保存消息失败:', error);
                        }
                    }

                    // 切换到聊天列表界面
                    this.loadChatList();
                    this.currentView = 'chatList';
                },

                // 加载聊天列表
                async loadChatList() {
                    try {
                        this.chatList = await this.db.getAllChats();
                    } catch (error) {
                        console.error('加载聊天列表失败:', error);
                        this.$message.error('加载聊天列表失败');
                    }
                },

                // 打开聊天
                async openChat(chat) {
                    this.currentChat = chat;
                    
                    try {
                        this.currentMessages = await this.db.getMessages(chat.id);
                        this.currentView = 'chat';
                        
                        // 清除未读标记
                        chat.unread = 0;
                        await this.db.addChat(chat);
                        
                        // 更新聊天列表
                        await this.loadChatList();
                        
                        // 滚动到底部
                        this.$nextTick(() => {
                            this.scrollToBottom();
                        });
                    } catch (error) {
                        console.error('加载聊天记录失败:', error);
                        this.$message.error('加载聊天记录失败');
                    }
                },

                // 发送消息
                async sendMessage() {
                    if (!this.newMessage.trim()) return;

                    // 创建消息对象
                    const message = {
                        chatId: this.currentChat.id,
                        type: 'sent',
                        content: this.newMessage,
                        timestamp: Date.now()
                    };

                    // 保存到数据库
                    try {
                        await this.db.addMessage(message);
                        
                        // 添加到当前消息列表
                        this.currentMessages.push(message);
                        
                        // 清空输入框
                        this.newMessage = '';
                        
                        // 滚动到底部
                        this.scrollToBottom();
                        
                        // 模拟回复消息
                        setTimeout(() => {
                            this.receiveMessage();
                        }, 2000);
                    } catch (error) {
                        console.error('发送消息失败:', error);
                        this.$message.error('发送消息失败');
                    }
                },

                // 接收消息
                async receiveMessage() {
                    const replies = [
                        '好的，我知道了',
                        '稍后回复你',
                        '这个想法不错',
                        '谢谢你的消息',
                        '我在忙，稍后详聊'
                    ];
                    
                    const reply = replies[Math.floor(Math.random() * replies.length)];
                    
                    const message = {
                        chatId: this.currentChat.id,
                        type: 'received',
                        content: reply,
                        timestamp: Date.now()
                    };

                    try {
                        await this.db.addMessage(message);
                        this.currentMessages.push(message);
                        this.scrollToBottom();
                        
                        // 更新聊天列表
                        this.currentChat.lastMessage = reply;
                        this.currentChat.lastTime = Date.now();
                        await this.db.addChat(this.currentChat);
                        await this.loadChatList();
                    } catch (error) {
                        console.error('接收消息失败:', error);
                    }
                },

                // 滚动到底部
                scrollToBottom() {
                    this.$nextTick(() => {
                        const container = this.$refs.messageContainer;
                        if (container) {
                            container.scrollTop = container.scrollHeight;
                        }
                    });
                },

                // 格式化时间
                formatTime(timestamp) {
                    const date = new Date(timestamp);
                    const now = new Date();
                    
                    // 如果是今天，只显示时间
                    if (date.toDateString() === now.toDateString()) {
                        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                    }
                    
                    // 如果是昨天，显示"昨天"
                    const yesterday = new Date(now);
                    yesterday.setDate(yesterday.getDate() - 1);
                    if (date.toDateString() === yesterday.toDateString()) {
                        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                    }
                    
                    // 其他情况显示日期
                    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
                }
            }
        });
    </script>
</body>
</html>